package blog.controller;

import blog.common.CacheService;
import blog.common.Result;
import blog.entity.Article;
import blog.entity.ArticleContent;
import blog.entity.ArticleType;
import blog.entity.User;
import blog.service.ArticleContentService;
import blog.service.ArticleService;
import blog.service.ArticleTypeService;
import blog.service.UserActionService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleContentService articleContentService;
    @Autowired
    private ArticleTypeService articleTypeService;
    @Autowired
    private UserActionService userActionService;

    /**
     * 分页查询文章类型
     */
    @GetMapping("/selectTypeByPage")
    public Result selectByPage(Integer page, Integer pageSize, String name) {
        LambdaQueryWrapper<ArticleType> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            wrapper.like(ArticleType::getTypeName, name);
        }
        Page<ArticleType> page1 = new Page<>(page, pageSize);
        Page<ArticleType> page2 = articleTypeService.page(page1, wrapper);
        return Result.success(page2);

    }
    /**
     * 添加文章类型
     */
    @PostMapping("/addArticleType")
    public Result addArticleType(@RequestBody ArticleType articleType) {
        articleTypeService.save(articleType);
        //添加文章类型后，将redis中的文章类型缓存清除
        cacheService.delete("allArticleType");
        return Result.success("添加成功");
    }
    /**
     * 删除文章类型
     */
    @DeleteMapping("/deleteArticleType/{id}")
    public Result deleteArticleType(@PathVariable("id") Integer id) {
        articleTypeService.removeById(id);
        //删除文章类型后，将redis中的文章类型缓存清除
        cacheService.delete("allArticleType");
        return Result.success("删除成功");
    }
    /**
     * 修改文章类型
     */
    @PutMapping("/updateArticleType")
    public Result updateArticleType(@RequestBody ArticleType articleType) {
        articleTypeService.updateById(articleType);
        //修改文章类型后，将redis中的文章类型缓存清除
        cacheService.delete("allArticleType");
        return Result.success("修改成功");
    }

    /**
     * 根据id查找文章类型
     */
    @GetMapping("/findArticleTypeById")
    public Result findArticleTypeById(Integer id) {
        ArticleType articleType = articleTypeService.getById(id);
        return Result.success(articleType);
    }


@Autowired
private CacheService cacheService;
    /**
     * 查找所有文章类型
     */
    @GetMapping ("/findAllArticleType")
    public Result findAllArticleType() {
        //使用redis缓存
        if (cacheService.exists("allArticleType")) {
            String json = cacheService.get("allArticleType");
            return Result.success(JSON.parseArray(json, ArticleType.class));
        }

        List<ArticleType> list = articleTypeService.list();
        //将list格式化为json字符串
        cacheService.set("allArticleType", JSON.toJSONString(list));
        return Result.success(list);

    }
    /**
     * 分页查找所有文章
     */
    @PostMapping("/findAllArticle")
    public Result findAllArticle(@RequestBody Map map) {
        int current = Integer.parseInt(map.get("current").toString());
        int size = Integer.parseInt(map.get("size").toString());
        return articleService.findAllArticle(current,size);
    }
    /**
     * 根据文章类型分页查找文章
     */
    @PostMapping("/findArticleByType")
    public Result findArticleByType(@RequestBody Map map) {
        int current = Integer.parseInt(map.get("current").toString());
        int size = Integer.parseInt(map.get("size").toString());
        int typeId = Integer.parseInt(map.get("typeId").toString());
        return articleService.findArticleByType(current, size, typeId);
    }
    /**
     * 文章访问量+1
     */
    @PutMapping("/addArticleVisitCount")
    public Result addArticleVisitCount(@RequestBody Map map) {
        int id = Integer.parseInt(map.get("aid").toString());
        return articleService.addArticleVisitCount(id);
    }

    /**
     * 根据文章标题查找文章
     */
    @PostMapping("/findArticleByTitle")
    public Result findArticleByTitle(@RequestBody Map map) {
        int current = Integer.parseInt(map.get("current").toString());
        int size = Integer.parseInt(map.get("size").toString());
        String title = map.get("title").toString();
        return articleService.findArticleByTitle(current, size, title);
    }
    /**
     * 查id为a到b的文章
     *
     */
    @PostMapping("/findArticleFromAtoB")
    public Result findArticleById(@RequestBody Map map) {
        int a = Integer.parseInt(map.get("a").toString());
        int b = Integer.parseInt(map.get("b").toString());
        return articleService.findArticleFromAtoB( a, b);
    }

    /**
     * 根据文章类型id查找文章类型
     */
    @PostMapping("/findArticleTypeById")
    public Result findArticleTypeById(@RequestBody Map map) {
        int id = Integer.parseInt(map.get("id").toString());
        return articleTypeService.findArticleTypeById(id);
    }

    /**
     * 添加文章
     */
    @PostMapping("/addArticle")
    @Transactional
    public Result addArticle(@RequestBody Article article) {
        boolean save = articleService.save(article);
        //添加空的文章内容
        ArticleContent articleContent = new ArticleContent();
        articleContent.setAid(article.getId());
        articleContent.setContent("");
        articleContentService.save(articleContent);
        if (save) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }

    }
    /**
     * 删除文章和文章内容，开启事务
     */
    @DeleteMapping("/deleteArticle/{id}")
    @Transactional
    public Result deleteArticle(@PathVariable("id") Integer id) {
        articleService.removeById(id);
        articleContentService.remove(new QueryWrapper<ArticleContent>().eq("a_id", id));
        return Result.success("删除成功");
    }
    /**
     * 修改文章
     */
    @PutMapping("/updateArticle")
    public Result updateArticle(@RequestBody Article article) {
        //查询article表中的数据
        Article article1 = articleService.getById(article.getId());
        //创键时间不变
        article.setCreateTime(article1.getCreateTime());

        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        article.setUpdateTime(now);
        articleService.updateById(article);
        return Result.success("修改成功");
    }
    /**
     * 添加文章内容
     */
    @PostMapping("/addArticleContent")
    public Result addArticleContent(@RequestBody ArticleContent articleContent) {
        boolean save = articleContentService.save(articleContent);
        if (save) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }
    /**
     * 修改文章内容
     */
    @PutMapping("/updateArticleContent")
    public Result updateArticleContent(@RequestBody ArticleContent articleContent) {
      //根据文章id查询文章内容
        ArticleContent articleContent1 = articleContentService.getOne(new QueryWrapper<ArticleContent>().eq("a_id", articleContent.getAid()));

        articleContent1.setContent(articleContent.getContent());
        articleContentService.updateById(articleContent1);
        return Result.success("修改成功");
    }

    /**
     * 根据文章id查找文章内容
     */
    @GetMapping("/findArticleContentById/{id}")
    public Result findArticleContentById(@PathVariable("id") int id) {
        ArticleContent articleContent = articleContentService.getOne(new QueryWrapper<ArticleContent>().eq("a_id", id));
        if (articleContent != null) {
            return Result.success(articleContent);
        } else {
            return Result.error("文章内容不存在");
        }
    }

    /**
     * 根据文章id查找文章
     */
    @GetMapping("/findArticleById/{id}")
    public Result findArticleById(@PathVariable("id") int id) {
        Article article = articleService.getOne(new QueryWrapper<Article>().eq("id", id));
        if (article != null) {
            return Result.success(article);
        } else {
            return Result.error("文章不存在");
        }
    }

    /**
     * 分页查询文章和文章类型名称
     */
    @GetMapping("/findArticleAndArticleType")
    public Result findArticleAndArticleType(Integer page, Integer pageSize, String name) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        //按照创建时间降序
        wrapper.orderByDesc(Article::getCreateTime);
        if (StringUtils.isNotBlank(name)) {
            wrapper.like(Article::getTitle, name);
        }
        Page<Article> page1 = new Page<>(page, pageSize);
        Page<Article> page2 = articleService.page(page1, wrapper);
        List<Article> records = page2.getRecords();
        List<ArticleType> list = new ArrayList<>();
        for (Article record : records) {
            ArticleType articleType = articleTypeService.getOne(new QueryWrapper<ArticleType>().eq("id", record.getTypeId()));
            list.add(articleType);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("article", page2);
        map.put("articleType", list);
        return Result.success(map);


    }




}



